package com.jar.netty_demo.Netty.dubbo.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * 异步转同步
 */
public class NettyClientHandle extends ChannelInboundHandlerAdapter implements Callable<String> {
    private ChannelHandlerContext ctx;
    private String result;
    private String param;

    /**
     * 2、
     *
     * @param param
     */
    public void setParam(String param) {
        this.param = param;
    }

    /**
     * 4、根据协议头获取bean,然后反向代理调用其方法
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        this.result = msg.toString();
        notify();
        System.out.println("msg:" + msg);
    }

    /**
     * 1、
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.ctx = ctx;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    /**
     * 3、调用此方法的时候要阻塞等待同步消息过来（异步转同步）
     */
    @Override
    public synchronized String call() throws InterruptedException {
        ctx.writeAndFlush(param);
        // 阻塞
        wait();
        return result;
    }
}
